﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

var sw = Stopwatch.StartNew();
var result = FibonacciGenerator().Take(40).LastOrDefault();
//var result = FibonacciRecursion(40);
//var result = FibonacciTail(40, 1, 1);
Console.WriteLine($"{result} {sw.Elapsed}");
Console.ReadKey();


// 递归实现
int FibonacciRecursion(int n)
{
    if (n < 2)
    {
        return n;
    }
    else
    {
        return FibonacciRecursion(n - 1) + FibonacciRecursion(n - 2);
    }
}

// 尾递归实现
int FibonacciTail(int n, int acc1, int acc2)
{
    if (n < 2)
    {
        return acc1;
    }
    else
    {
        Console.WriteLine($"factorial_tail({n - 1}, {acc2}, {acc1})");
        return FibonacciTail(n - 1, acc2, acc1 + acc2);
    }
}

// 生成器实现
IEnumerable<int> FibonacciGenerator()
{
    int current = 1, next = 1;

    while (true)
    {
        yield return current;
        next = current + (current = next);
    }
}
